import  { modules } from '../services/modules.js'
import router from 'umi/router'
import AllModules from '../utils/modules'
import asyncComponent from '../utils/asyncComponent'
export default {
  namespace: 'modules',
  state:{
    modulesArray: [],
    pathname: '',
    showList:[],
    title: '',
    query: {}
  },
  subscriptions: {
    // 判断是否进入的是首页 如果是首页需要还原state的状态 否则重新进入一个新的流程会出现闪现的现象 会闪现之前流程的内容
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/homePage' || '/homepage') {
         dispatch({
           type: 'changeModules',
           payload: {
             modulesArray:[],
             pathname:'',
             showList:[],
             title:''
           }
         })
        }
      })
    }
  },
  effects: {
    *getModules ({ payload },{ call, put }) {
      const { data } = yield call(modules, payload)
      let { templateIdSeq } = data.data.businessProcessVo
      let { pathname , process , title, query} = payload
      let list = []
      templateIdSeq.slice(1).map( (item) => {
        if (AllModules[item] && process) {
          let one = asyncComponent(()=> import(`../pages/${process}/components/${AllModules[item]}.js`))
          list.push(one)
        }
        return list
      })
      yield put({
        type: 'changeModules',
        payload: {
          modulesArray: templateIdSeq,
          pathname: pathname,
          showList: list,
          title: title,
          query:query
        }
      })
      // 如果用户是按钮请求传参pathname进行跳转,除此之外用户有可能只是刷新页面发出ajax请求但是不需要跳转
      if (pathname) {
        router.push({
          pathname
        })
      }
    },
  },
  reducers: {
    changeModules (state, { payload }) {
      return {
        state,
        ...payload
      }
    }
  }
}